/*
 *  Copyright 2011-2012 Redia A/S
 * 
 *  This file is part of Redias Android Utilities.
 *
 *  Redias Android Utilities is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Redias Android Utilities is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Redias Android Utilities.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.redia.lib.utils;

import android.text.SpannableString;
import android.text.style.URLSpan;
import android.text.util.Linkify;

public class StringUtils {
	
	public static String linkify(String target) {
	    SpannableString ss = new SpannableString(target);
	    Linkify.addLinks(ss, Linkify.ALL);
	    URLSpan[] spans = ss.getSpans(0, ss.length(), URLSpan.class);

	    StringBuffer result = new StringBuffer(target.length());
	    int previousEnd = 0;
	    
	    for (URLSpan urlSpan : spans) {

	    	// Where does the current span start and end in the 
	    	// original string
			int start = ss.getSpanStart(urlSpan);
			int end = ss.getSpanEnd(urlSpan);
	    	// Copy chunk from previous end to current start to
	    	// result buffer
	    	result.append(target.substring(previousEnd, start));
	    	String buf = target.substring(start, end);
	    	result.append("<a href=\"" + urlSpan.getURL() + "\">" + buf + "</a>");
	    	previousEnd = end;
		}
	    result.append(target.substring(previousEnd, target.length()));
	    
	    return result.toString();
	    
	}
	
	public static String firstToUpperCase(String target) {
		if (target!=null && target.length()>0) {
			return Character.toUpperCase(target.charAt(0)) + target.substring(1);
		} else {
			return target;
		}
	}
}
